import React, { useEffect, useRef, useState } from 'react'
import { ProTable } from '@ant-design/pro-components'
import { App, Button, Space, Table, Popconfirm } from 'antd'
import { useModel } from '@umijs/max'
import './BillList.less'
import dayjs from 'dayjs'
import { DownloadOutlined } from '@ant-design/icons'
import { render } from 'react-dom'

export default () => {
  const { message, modal } = App.useApp()
  const { GetFinanceRecord, GetTransactionType, GetFinanceBillList, GetStatusMap } = useModel('Withdrawal')
  const { GetShopSelections } = useModel('Goods')
  const { platformType, CheckOptionAuth } = useModel('Global')
  const { BillPlatExport, BillMchExport } = useModel('DownloadCenter')
  const proTableFormRef = useRef()

  const tableRef = useRef()

  const [currentPage, setCurrentPage] = useState(1) //  当前页码
  const [pageSize, setPageSize] = useState(10) //  每页数量

  const [amountTotal, setAmountTotal] = useState({}) // 交易金额总计
  const [shopList, setShopList] = useState([]) // 所属店铺列表
  const [tradeTypeList, setTradeTypeList] = useState([]) // 交易类型
  const [orderStatusList, setOrderStatusList] = useState({}) // 订单状态列表

  useEffect(() => {
    getShopList()
    getTradeType()
    getOrderStatusList()
  }, [])

  const getOrderStatusList = async () => {
    const res = await GetStatusMap()
    if (res) {
      let obj = {}
      res.forEach(i => {
        obj[i.status] = i.status_desc
      });
      setOrderStatusList(obj)
    }
  }

  //  获取店铺列表
  const getShopList = async () => {
    const res = await GetShopSelections()
    setShopList(res.map(i => [i.id, i.shop_name]))
  }

  // 获取交易类型
  const getTradeType = async () => {
    const res = await GetTransactionType()

    let arr = []
    for (const resKey in res) {
      arr.push({
        id: resKey,
        value: res[resKey]
      })
    }

    arr && setTradeTypeList(arr.map(i => [i.id, i.value]))
  }

  // 基础-列
  const baseColumns = [
    {
      title: 'ID',
      dataIndex: 'order_id',
      width: 80,
      hideInSearch: true
    },
    {
      title: '交易类型',
      dataIndex: 'type_desc',
      width: 100,
      valueType: 'select',
      valueEnum: new Map(tradeTypeList),
      fieldProps: {
        mode: 'multiple'
      }
    },
    {
      title: '交易金额',
      dataIndex: 'amount',
      hideInSearch: true,
      width: 100,
      render: (text, record) => (
        <Space>
          {
            // 2 退款  25 提现
            text === '0.00' ? (
              <span style={{ color: '#333' }}>0.00元</span>
            ) : record.type === 25 || record.type === 2 ? (
              <span style={{ color: '#FE3850' }}>-{text}元</span>
            ) : (
              <span style={{ color: '#12D2AC' }}>+{text}元</span>
            )
          }
        </Space>
      )
    },
    {
      title: '实际结算金额',
      dataIndex: 'settle_amount',
      hideInSearch: true,
      width: 100,
      render: (text, record) => (
        <Space>
          {
            // 2 退款  25 提现
            text === '0.00' ? (
              <span style={{ color: '#333' }}>0.00元</span>
            ) : record.type === 25 || record.type === 2 ? (
              <span style={{ color: '#FE3850' }}>-{text}元</span>
            ) : (
              <span style={{ color: '#165DFF' }}>+{text}元</span>
            )
          }
        </Space>
      )
    },
    {
      title: '手续费',
      dataIndex: 'rate_amount',
      hideInSearch: true,
      width: 100,
      render: (text, record) => (
        <div>
          {record.type === 2 ? (
            <span style={{ color: '#FE3850' }}>-{text}元</span>
          ) : (
            <span style={{ color: '#F56D25' }}>{text}元</span>
          )}
        </div>
      )
    },
    {
      title: '交易后余额',
      dataIndex: 'after_amount',
      hideInSearch: true,
      width: 100,
      render: (text, record) => <div>{text}元</div>
    },
    {
      title: '交易流水号',
      dataIndex: 'out_trade_no',
      width: 200,
      render: (text, record) => <p style={{ width: '180px', wordWrap: 'break-word' }}>{text}</p>
    },
    {
      title: '结算状态',
      dataIndex: 'settle_flag',
      width: 120,
      align: 'center',
      valueEnum: {
        0: '待结算',
        1: '已结算'
      },
      render: text => {
        return <b>{text}</b>
      }
    },
    {
      title: '订单信息',
      hideInSearch: true,
      width: 300,
      render: (text, record) => (
        <div>
          <p>订单编号 : {record.order_sn ? record.order_sn : '-'}</p>
          <p>下单时间 : {record.order_created_at ? record.order_created_at : '-'}</p>
        </div>
      )
    },
    {
      title: '订单编号',
      dataIndex: 'order_sn',
      hideInTable: true,
      width: 200
    },
    {
      title: '用户姓名',
      dataIndex: 'user_name',
      width: 100
    },
    {
      title: '订单状态',
      dataIndex: 'status_desc',
      hideInSearch: true,
      width: 100
    },
    {
      title: '交易时间',
      dataIndex: 'created_at',
      width: 200,
      // valueType: 'dateRange',
      valueType: 'dateTimeRange',
      render: (text, record) => <p>{record.created_at}</p>,
      search: {
        transform: value => {
          return {
            created_at_start: dayjs(value[0]['$d'] || value[0]).format('YYYY-MM-DD HH:mm:ss'),
            created_at_end: dayjs(value[1]['$d'] || value[1]).format('YYYY-MM-DD HH:mm:ss')
          }
        }
      }
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      width: 120,
      hideInTable: true,
      align: 'center',
      valueEnum: orderStatusList
    }
  ]

  // 平台端-列
  const platformColumns = [...baseColumns]
  platformColumns.splice(-2, 0, {
    title: '归属店铺',
    dataIndex: 'shop_name',
    width: 100,
    valueType: 'select',
    valueEnum: new Map(shopList),
    fieldProps: {
      mode: 'multiple'
    },
    render: (text, record) => <a onClick={() => {}}>{text}</a>
  })

  // 商家端-列
  const merchantColumns = [...baseColumns]

  const columns = platformType === 0 ? platformColumns : merchantColumns


  // 导出数据---------------
  const handleExportTable = async () => {
    // 获取当前路由菜单名称
    // const routerName = subRoutes.filter(item => item.path.match(location.pathname))?.[0]?.name

    const params = proTableFormRef.current.getFieldsValue()

    let filter = {
      order_sn: params.order_sn,
      out_trade_no: params.out_trade_no,
      user_name: params.user_name,
      merchant_id: params.shop_name,
      type: params.type_desc,
      created_at_start: params.created_at_start,
      created_at_end: params.created_at_end,
      settle_flag: params.settle_flag,
      status: params.status,

      created_at_start:
        params.created_at &&
        params.created_at.length &&
        dayjs(params.created_at[0]['$d']).format('YYYY-MM-DD HH:mm:ss'),
      created_at_end:
        params.created_at &&
        params.created_at.length &&
        dayjs(params.created_at[1]['$d']).format('YYYY-MM-DD HH:mm:ss'),

      // channel_type: 'e_card', // single:独立部署    saas:saas项目  green:绿植项目  e_card:E卡项目
      // platform_id: userInfo.pf_id,
      // admin_user_id: userInfo.id,
      // login_type: userInfo.login_type,
      // route_menu_name: (sellType ? '电商订单_' : '租赁订单_') + routerName,
      // life_type: sellType ? 1 : 0 // 0  租赁订单  1 电商订单
    }

    // if (tabActiveKey && tabActiveKey !== 'all_order') {
    //   const item = originTabs.find(i => i.key === tabActiveKey)
    //   filter.status = item.status
    //   filter.special_day_tips = item.special_day_tips
    //   filter.in_after_sale = item.in_after_sale
    //   filter.become_due = item.become_due
    // }

    const method = platformType ? BillMchExport : BillPlatExport
    const res = await method(filter)

    if (res) {
      message.success('数据导出成功，请在顶部导航【导出中心】下载内容')
    }
  }

  return (
    <>
      <ProTable
        actionRef={tableRef}
        formRef={proTableFormRef}
        request={async params => {
          const filters = {
            order_sn: params.order_sn,
            out_trade_no: params.out_trade_no,
            user_name: params.user_name,
            merchant_id: params.shop_name,
            type: params.type_desc,
            created_at_start: params.created_at_start,
            created_at_end: params.created_at_end,
            settle_flag: params.settle_flag,
            status: params.status,
          }

          const param = {
            page: params.current,
            page_size: params.pageSize,
            ...filters
          }

          setCurrentPage(params.current)
          setPageSize(params.pageSize)

          const res = platformType === 0 ? await GetFinanceRecord(param) : await GetFinanceBillList(param)
          setAmountTotal(res.other)

          return {
            data: res.data,
            success: true,
            total: res.total
          }
        }}
        summary={pageData => {
          return (
            <>
              <Table.Summary.Row>
                <Table.Summary.Cell index={0}>
                  <div className='summary_cell'>总计</div>
                </Table.Summary.Cell>
                {
                  <>
                    <Table.Summary.Cell index={1}>-</Table.Summary.Cell>
                    <Table.Summary.Cell index={2}>
                      <div className='summary_cell'>{amountTotal.amountSum} 元</div>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={3}>
                      <div className='summary_cell'>{amountTotal.totalSettleAmount}元</div>
                    </Table.Summary.Cell>
                    <Table.Summary.Cell index={4}>
                      <div className='summary_cell'>{amountTotal.rateAmountSum} 元</div>
                    </Table.Summary.Cell>
                  </>
                }
              </Table.Summary.Row>
            </>
          )
        }}
        pagination={{
          pageSize: pageSize,
          current: currentPage
        }}
        rowKey='id'
        scroll={{ x: 'max-content' }}
        columns={columns}
        toolBarRender={() => [
          

          CheckOptionAuth('exportBillData') ? (
            <Popconfirm
              key='export'
              title='确认导出账单?'
              description='确认导出账单后，将在导出中心生成账单数据文件，请在导出中心下载。'
              onConfirm={() => handleExportTable()}
              okText='确认导出'
              cancelText='取消'
              okType='primary'
            >
              <Button icon={<DownloadOutlined />}>导出数据</Button>
            </Popconfirm>
          ) : null
        ]}
        search={{
          defaultCollapsed: false,
          labelWidth: 80,
          span: 8
        }}
      />
    </>
  )
}
